const fs = require("fs");
const jschardet = require('jschardet')
const xlsx = require('node-xlsx')
const send = require('koa-send')
const common = require('lib/utils/common.js')
const db = require('db/place.js')

/** @name 导入车位 **/
exports.importController = async ctx => {
	const excelKeys = ['车位编号', '是否是固定车位', '车牌号码'];
	const dbKeys = ['code', 'type', 'number'];
	// 文件处理
	const files = ctx.req.files.file;
	const filePath = files[0].path;
	const fileContent = fs.readFileSync(filePath);
	const fileEncoding = jschardet.detect(fileContent).encoding; // 'UTF-8' or 'GB2312' or null
	const excelData = fileEncoding === 'GB2312'
		? handleCSV(filePath, excelKeys, dbKeys)
		: handleXLSX(filePath, excelKeys, dbKeys);

	if(excelData.length === 0) return ctx.fail('当前上传文件无数据');

	const createTime = common.YD_dateFormat();

	const values = [];
	excelData.forEach(item => {
		values.push([
			item.code,
			item.type === '是' ? 1 : 0,
			item.number,
			createTime,
			createTime
		]);
	})

	await db.yd_batchInsert(values);

	ctx.success(values.length);
};

/** @name 处理正常编码的excel文件 **/
function handleXLSX(path, excelKeys, dbKeys) {
	let sheets = xlsx.parse(path);
	let array = sheets[0].data; // 二维数组
	if(array.length === 0) return [];
	let header = array[0]; // 获取Excel表头
	let headerIndexs = excelKeys.map(key => header.indexOf(key));
	let result = [];
	array.forEach((row, index) => {
		if(index > 0) {
			let o = {};
			headerIndexs.forEach((idx, i) => {
				o[dbKeys[i]] = row[idx];
			})
			o.code && result.push(o);
		}
	})
	return result;
}

/** @name 下载模版 **/
exports.download = async ctx => {
	const path = `public/template/001-车位导入模版.xlsx`
  ctx.attachment(path)
  await send(ctx, path)
};

/** @name 车位列表 **/
exports.list = async ctx => {
	const { code, idle, type, number, realname, phone } = ctx.query;
	const options = {
		...common.YD_getPageDefault(ctx),
		code, idle, type, number, realname, phone
	}
	const totalRes = await db.yd_count(options);
  const total = totalRes[0].count || 0;
  const rows = await db.yd_list(options);
	ctx.success({
    total,
    rows
  });
};

/** @name 添加车位 **/
exports.add = async ctx => {
	if(ctx.requiredParams(['code', 'type', 'idle'])) return;
	const { code, type, userId, number, idle, images, note } = ctx.request.body;
	const currentTime = common.YD_dateFormat()
	const options = {
		code,
		type: common.YD_isUndefined(type, 0),
		userId,
		number,
		idle: common.YD_isUndefined(idle, 0),
		images,
		note,
		createTime: currentTime,
		updateTime: currentTime,
	}
	await db.yd_add(options);
	ctx.success('车位添加成功');
};

/** @name 编辑车位 **/
exports.edit = async ctx => {
	if(ctx.requiredParams(['code', 'type', 'idle', 'id'])) return;
	const { code, type, userId, number, idle, images, note, id } = ctx.request.body;
	const currentTime = common.YD_dateFormat()
	const options = {
		code,
		type: common.YD_isUndefined(type, 0),
		userId,
		number,
		idle: common.YD_isUndefined(idle, 0),
		images,
		note,
		updateTime: currentTime,
	}
	await db.yd_update(options, { id });
	ctx.success('车位编辑成功');
};

/** @name 删除车位 **/
exports.delete = async ctx => {
	if(ctx.requiredParams(['id'])) return;
	const { id } = ctx.request.body;
	await db.yd_delete(id);
	ctx.success('车位删除成功');
};

/** @name 设置固定车位 **/
exports.fixed = async ctx => {
	if(ctx.requiredParams(['id', 'userId'])) return;
	const { id, userId, number } = ctx.request.body;
	const options = {
		userId,
		number,
		updateTime: common.YD_dateFormat(),
	}
	await db.yd_update(options, { id });
	ctx.success('设置固定车位成功');
};

/** @name 设置车位是否是空闲 **/
exports.idle = async ctx => {
	if(ctx.requiredParams(['id', 'idle'])) return;
	const { id, idle } = ctx.request.body;
	const options = {
		idle,
		updateTime: common.YD_dateFormat(),
	}
	await db.yd_update(options, { id });
	ctx.success('设置成功');
};

/** @name 简易查询全部车位列表 **/
exports.easyList = async ctx => {
  const rows = await db.yd_easyList();
	ctx.success({
    rows
  });
};
